package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-06
 * Time: 21:11
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String severIp;//服务器ip
    private int severPort;//服务器端口

    public UdpEchoClient(String severIp, int severPort) throws SocketException {
        //对于客户端不必显示关联端口，系统会自动分配空闲的端口
        socket = new DatagramSocket();
        this.severIp = severIp;
        this.severPort = severPort;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        //通过客户端多次和服务器交互
        while (true) {
            //1. 先从控制台读取字符串
            System.out.println("->");
            String request = scanner.next();
            //2. 把字符串构造成UDPPacket，并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.length(), InetAddress.getByName(severIp), severPort);
            socket.send(requestPacket);
            //3. 客户端尝试读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //4. 把响应数据转换成String
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("req: %s, resp: %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
